<template>
  <view class="">
    <view class="upload-list">
      <view v-for="(item, index) in lists" :key="index" class="dd ">
          <image :src="item.url" mode="aspectFill" class="img" @click="previewImg($event,item.url)"></image>
          <text class="close" @click="close(item.url)" v-if="list.length === 0"></text>
      </view>
      <view class="dd add" style="display: flex; align-items: center; justify-content: center; text-align: center;" v-if="list.length === 0" @click="uploadImgs">
      	<view>
          <image src="../static/image/index/xj.png" style="width: 50rpx; height: 50rpx; display: block; margin: 0 auto 10rpx;" mode="aspectFit"></image>
          <view style="font-size: 28rpx; color: #888;">点击拍照</view>
        </view>
      </view>
    </view>
  </view>
  
</template>

<script>
export default {
  name: 'zbTitle',
  props:{
    list:Array,
  },
  data() {
  	return {
      uploading:false,
      lists:[]
  	}
  },
  mounted() {
    this.lists = this.list || [];
    console.log('this.list===>',this.list)
  },
  methods: {
    downImgClick(){
      this.lists.forEach(n => {
        console.log(n.fullurl)
        this.downImg(n.fullurl)
      })
    },
    downImg(url) {
      console.log('urlurlurlurlurlurlurlurl=====>',url)
      if(!url){
        console.log('图片获取失败，请稍后再试')
        return;
      }
      wx.showLoading({
        title: '加载中...',
      })
      //图片保存到本地
      wx.downloadFile({
        url: url,//图片地址
        success (downres) {
          // 保存图片到相册
          wx.saveImageToPhotosAlbum({
            filePath: downres.tempFilePath,
            success(res) {
              wx.hideLoading()
              console.log('保存成功')
            },
            fail(err){
              wx.hideLoading()
              if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
                wx.showModal({
                  title: '提示',
                  content: '请授权保存到相册',
                  showCancel: false,
                  success() {
                    wx.openSetting({
                      success(openres) {
                        console.log("openres", openres)
                        if (openres.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，再次点击图片即可保存')
                        } else {
                          console.log('获取权限失败，无法保存到相册哦~')
                        }
                      },
                      fail(failerr) {
                        console.log("failerr", failerr)
                      }
                    })
                  }
                })
              }
            }
          })
        },
        fail() {
          wx.hideLoading()
          console.log('下载失败，请稍后再试')
        }
      })
    },
    previewImg(e, url){
      const list = this.lists.map(m=>{
        return m.url
      })
      uni.previewImage({
        urls: list,
        longPressActions: {
          itemList: ['发送给朋友', '保存图片', '收藏'],
          success: function(data) {
            console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
          },
          fail: function(err) {
            console.log(err.errMsg);
          }
        }
      });
      
    },
    // 选择图片并上传
    uploadImgs(){
      if(this.lists.length < 2){
        const that = this;
        uni.chooseImage({
          count:2,
        	success: (res) => {
        		const tempFilePaths = res.tempFilePaths;
            tempFilePaths.forEach(n=>{
              that.upAjax(n)
              // const time = new Date().getTime()
              // this.lists = this.lists.concat({url:n, fullurl:n, id:time});
              // this.$emit('bakUrl',this.lists)
            })
        		
        	},
        });
      }else{
        uni.showToast({
          title:'最多上传两张图片',
          icon:'none'
        })
      }
    },
    close(url){
      this.lists = this.lists.filter(n => n.url !== url)
    },
    upAjax(url){
      const time = new Date().getTime()
      this.uploading=true
      uni.uploadFile({
      	url: this.$api.uploadImageApi, //仅为示例，非真实的接口地址
      	filePath: url,
      	name: 'file',
      	success: (res) => {
          res = JSON.parse(res.data);
          console.log('res=======>',res)
          if(res.code === 200){
            this.lists = this.lists.concat({url:res.data.file_path_all, id:time});
            // const files = this.lists.map(m => {
            //   return m.url
            // });
            // console.log('files====>',files)
            this.$emit('getImages',this.lists)
          }
          
      	},
        complete:res=>{
          this.uploading=false
        }
      });
    }
  }
  	
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
	
		.loading {
    width: 100%;
    height: 100%;
    position: relative;
    background: #F5F5F9;
    z-index: 999;
		}
		.loading::before {
			content: '';
			position: absolute;
			display: inline-block;
			width: 40rpx;
			height: 40rpx;
			border-radius: 50%;
			border: 2rpx solid #ccc;
			border-top-color: #333;
			animation: spin 1s ease-in-out infinite;
			left: calc(50% - 22rpx);
			top: calc(50% - 22rpx);
		}
		@keyframes spin {
			to {
				-webkit-transform: rotate(360deg);
				transform: rotate(360deg);
			}
		}
.tits{
  color: #427AFB; margin-bottom: 20rpx;
  .lab{flex: 1; color: #999;}
  .ico{width: 30rpx; height: 30rpx; margin-right: 10rpx;}
}

.upload-list{
  flex-wrap: wrap; width: 110%; display: flex; align-items: center; justify-content: flex-start; flex-wrap: wrap;
  .dd{
    width: 158rpx; height: 158rpx; position: relative; border-radius: 6rpx; background-color: aliceblue; margin: 0 16rpx 16rpx 0;
    .close{width: 36rpx; height: 36rpx; border-radius: 50%; background-color: red; position: absolute; right: 0; top: 0; transform: translate(30%,-50%) rotate(45deg);}
    .close::after,.close::before{background-color: #fff !important;}
    .img{border-radius: 6rpx; width: 100%; height: 100%;}
    &.add{background-color: #f5f5f5;}
    // &.add::after,&.add::before,.close::after,
    .close::before{content: ''; display: block; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); background-color: #ddd;}
    // &.add::after,
    .close::after{width: 60%; height: 4px; border-radius:10rpx;}
    // &.add::before,
    .close::before{width: 4px; height: 60%; border-radius:10rpx}
  }
  
}

</style>
